package com.bsj.travel.security.aspect;

import com.bsj.travel.security.annotation.RequiresPermissions;
import com.bsj.travel.security.annotation.RequiresRoles;
import com.bsj.travel.security.auth.AuthUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author yinhao
 * @version 1.0
 * @description 基于AOP的注解鉴权
 * @date 2024/1/10
 */
@Aspect
@Component
public class PreAuthAspect {
    public PreAuthAspect(){}

    public static final String POINTCUT_SIGN = "@annotation(com.bsj.travel.security.annotation.RequiresPermissions) ||"
            + "@annotation(com.bsj.travel.security.annotation.RequiresRoles)";

    /**
     * 声明AOP签名
     */
    @Pointcut(POINTCUT_SIGN)
    public void pointcut() {}

    /**
     * 切入
     * @param joinPoint 切面对象
     * @return 底层执行后的返回值
     * @throws Throwable 异常
     */
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //注解鉴权
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        checkMethodAnnotation(signature.getMethod());
        try {
            Object object = joinPoint.proceed();
            return object;
        } catch (Throwable e) {
            throw e;
        }
    }

    /**
     * 对于Method对象进行注解检查
     * @param method
     */
    public void checkMethodAnnotation(Method method) {
        //校验@RequiresRoles 注解
        RequiresRoles requiresRoles = method.getAnnotation(RequiresRoles.class);
        if(requiresRoles != null) {
            AuthUtil.checkRole(requiresRoles);
        }
        RequiresPermissions requiresPermissions = method.getAnnotation(RequiresPermissions.class);
        if (requiresPermissions != null) {
            AuthUtil.checkPerm(requiresPermissions);
        }
    }
}
